package cn.cf.kxx.tools;

import android.util.Log;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


/**
 * project name: SerialTools
 * package name: com.sz.zysj.serialtools
 * file name: SerialPort
 * author: Jason-Liang
 * create date and time: 2021/3/18 19:26
 */
public class SerialPort
    {

        private static final String TAG = "dong";

        /*
         * Do not remove or rename the field mFd: it is used by native method
         * close();
         */
        private FileDescriptor mFd;
        private FileInputStream mFileInputStream;
        private FileOutputStream mFileOutputStream;
//        public SerialPort() {}

        public SerialPort(File device, int baudrate, int flags) throws SecurityException, IOException
        {

            /* Check access permission */
            if (!device.canRead() || !device.canWrite())
            {
                try
                {
                    /* Missing read/write permission, trying to chmod the file */
                    Process su;
                    su = Runtime.getRuntime().exec("/system/xbin/su");
                    String cmd = "chmod 666 " + device.getAbsolutePath() + "\n" + "exit\n";
                    su.getOutputStream().write(cmd.getBytes());
                    if ((su.waitFor() != 0) || !device.canRead() || !device.canWrite())
                    {
                        throw new SecurityException();
                    }
                } catch (Exception e)
                {
                    e.printStackTrace();
                    throw new SecurityException();
                }
            }
            Log.i("lrm", "baudrate: " + baudrate);
            mFd = open(device.getAbsolutePath(), baudrate, flags);
            Log.e(TAG, mFd+":mFd");
            if (mFd == null)
            {
                Log.e(TAG, "native open returns null");
                throw new IOException();
            }
            mFileInputStream = new FileInputStream(mFd);
            mFileOutputStream = new FileOutputStream(mFd);
        }

        // Getters and setters
        public InputStream getInputStream()
        {
            return mFileInputStream;
        }

        public OutputStream getOutputStream()
        {
            return mFileOutputStream;
        }


    // JNI
    public native static FileDescriptor open(String path, int baudrate, int flags);
    public native String stringFromJNI();
    public native void close();

    // Used to load the 'kxx' library on application startup.
    static {
        System.loadLibrary("kxx");
    }



}
